<!doctype html>
<html lang="zh-cn">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="/static/bootstrap-5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/bootstrap-icons-1.11.1/bootstrap-icons.css" rel="stylesheet">
    <title>文件列表</title>
    <style>
        .disabled .spinner-border {
            display: inline-block!important;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div>
        <div class="bg-light p-2 fixed-top">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0">
                    <li class="breadcrumb-item"><a href="<?=url()?>">根目录</a></li>
                    <?php foreach ($breadcrumb as $item): ?>
                    <li class="breadcrumb-item"><a href="<?=$item['url']?>"><?=$item['name']?></a></li>
                    <?php endforeach; ?>
                </ol>
            </nav>
            <hr/>
            <button type="button" class="btn btn-primary" id="upload">上传</button>
            <button type="button" class="btn btn-danger" id="delete">删除</button>
            <button type="button" class="btn btn-primary">复制</button>
            <button type="button" class="btn btn-primary">剪切</button>
            <button type="button" class="btn btn-primary">粘贴</button>
        </div>
    </div>
    <div class="table-responsive" style="margin-top: 120px;">
        <table class="table table-hover">
            <thead>
            <tr>
                <th scope="col">
                    <input class="form-check-input" type="checkbox" id="checked-all" value="">
                </th>
                <th scope="col">名称</th>
                <th scope="col">日期</th>
                <th scope="col">大小</th>
                <th scope="col">操作</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach($list as $item): ?>
            <?php $basename = substr($item['path'], strlen($path)); ?>
            <tr>
                <td>
                    <input class="form-check-input" type="checkbox" name="checked[]" value="<?=$item['path']?>" data-type="<?=$item['type']?>" data-basename="<?=$basename?>">
                </td>
                <td>
                    <?php
                        switch($item['type']) {
                            case 'file': echo '<i class="bi bi-file-earmark"></i>'; break;
                            case 'dir': echo '<i class="bi bi-folder"></i>'; break;
                            default: echo '<i class="bi bi-question-circle"></i>'; break;
                        }
                    ?>
                    <?php if ('dir' == $item['type']) { ?>
                        <a href="<?=url('', ['path' => $item['path']])?>"><?=$basename?></a>
                    <?php } else { ?>
                        <?=$basename?>
                    <?php } ?>
                </td>
                <td><?=$item['lastModified'] ? date('Y-m-d H:i:s', $item['lastModified']) : ''?> </td>
                <td><?=$item['fileSize'] ?? ''?></td>
                <td>
                    <button type="button" class="btn btn-primary btn-sm option-rename">重命名</button>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<form class="modal" tabindex="-1" id="renameModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">重命名</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="path" value="">
                <input type="hidden" name="old" value="">
                <div class="mb-3">
                    <label for="rename-basename" class="form-label">新名称</label>
                    <input type="text" class="form-control" name="new" id="rename-basename" placeholder="请输入新名称">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary">
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display: none"></span>
                    修改
                </button>
            </div>
        </div>
    </div>
</form>
<form class="modal" tabindex="-1" id="uploadModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">上传文件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="path" value="<?=$path?>">
                <div class="mb-3">
                    <label for="upload-file" class="form-label">选择文件</label>
                    <input type="file" class="form-control" name="file" id="upload-file">
                </div>
                <div class="mb-3">
                    <label for="upload-filename" class="form-label">文件名称</label>
                    <input type="text" class="form-control" name="filename" id="upload-filename" placeholder="请输入文件名称">
                </div>
                <div class="progress">
                    <div class="progress-bar progress-bar-striped" role="progressbar" style="width: 0%"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary">
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display: none"></span>
                    上传
                </button>
            </div>
        </div>
    </div>
</form>
<form class="modal" tabindex="-1" id="deleteModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">删除文件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="path" value="<?=$path?>">
                <p class="text-danger">确定要删除以下文件或目录？</p>
                <ul class="list-group"></ul>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-danger">
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display: none"></span>
                    删除
                </button>
            </div>
        </div>
    </div>
</form>
<script src="/static/js/jquery.min.js"></script>
<script src="/static/bootstrap-5.3.2/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/popper.min.js"></script>
<script src="/static/bootstrap-5.3.2/js/bootstrap.min.js"></script>
<script>
    let renameModal = new bootstrap.Modal(document.getElementById('renameModal'), {backdrop: 'static'});
    let uploadModal = new bootstrap.Modal(document.getElementById('uploadModal'), {backdrop: 'static'});
    let deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'), {backdrop: 'static'});
    $('[name="checked[]"]').change(function (){
        if ($('[name="checked[]"]:not(:checked)').length > 0) {
            $('#checked-all').prop('checked', false);
        } else {
            $('#checked-all').prop('checked', true);
        }
    });

    $('#checked-all').change(function () {
        $('[name="checked[]"]').prop('checked', this.checked);
    });
    
    $('.option-rename').click(function () {
        let data = $(this).parents('tr').data();
        $('#renameModal [name="path"]').val(data.dirname);
        $('#renameModal [name="old"]').val(data.basename);
        $('#renameModal [name="new"]').val(data.basename);
        renameModal.show();
    });

    $('#renameModal').submit(function () {
        let submitButton = $(this).find('[type="submit"]');
        submitButton.addClass('disabled');

        fetch("<?=url('rename')?>", {
            body: new FormData(this)
            ,method: 'POST'
            ,credentials: 'same-origin'
            ,headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
            .then(response => response.json())
            .then(function (result) {
                submitButton.removeClass('disabled');

                if (0 == result.code) {
                    renameModal.hide();
                    alert(result.msg);
                    location.reload();
                } else {
                    alert(result.msg);
                }
            })
            .catch(function (error) {
                submitButton.removeClass('disabled');
                alert('发生错误:' + error);
            });
        return false;
    });

    $('#upload').click(function () {
        $('#uploadModal .progress-bar').css('width', '0').removeClass('progress-bar-animated');
        uploadModal.show();
    });
    $('#upload-file').change(function () {
        $('#upload-filename').val(this.files.length > 0 ? this.files[0].name : '');
    });
    $('#uploadModal').submit(function () {
        (async function (elem) {
            let submitButton = $(elem).find('[type="submit"]');
            let progressBar = $(elem).find('.progress-bar');
            submitButton.addClass('disabled');
            progressBar.addClass('progress-bar-animated');

            let formData = new FormData(elem)
                ,file = formData.get('file')
                ,blockSize = 1024 * 1024 * 1
                ,blockNum = Math.ceil(file.size / blockSize)
                ,start = 0
                ,end = 0
                ,progressWidth = '0%';

            if (0 == file.size) {
                return alert('请选择要上传的文件');
            }
            console.log(file);
            formData.append('blockSize', blockSize.toString());
            formData.append('blockNum', blockNum.toString());
            formData.append('fileSize', file.size.toString());
            try {
                for (let i = 1; i <= blockNum; i++) {
                    end += blockSize;
                    if (end > file.size) end = file.size;
                    formData.set('blockNo', i.toString());
                    formData.set('file', file.slice(start, end), file.name);
                    await fetch("<?=url('upload')?>", {
                        body: formData
                        ,method: 'POST'
                        ,credentials: 'same-origin'
                        ,headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                        .then(response => response.json())
                        .then(function (result) {
                            if (0 != result.code) {
                                throw result.msg;
                            }
                            console.log(start, end, end - start, result.data);
                        })
                        .catch(function (error) {
                            throw error;
                        });
                    start = end;
                    progressWidth = (i / blockNum * 100).toFixed(2).toString() + '%';
                    progressBar.css('width', progressWidth).text(progressWidth);
                }
            } catch (e) {
                console.log(e);
                alert('发生错误:' + e);
            }
            submitButton.removeClass('disabled');
            progressBar.removeClass('progress-bar-animated');
            location.reload();
        }(this));

        return false;
    });

    $('#delete').click(function () {
        let checkedList = $('input[name="checked[]"]:checked');
        let html = '';
        if (0 == checkedList.length) {
            return alert('请选择要删除的内容');
        }
        checkedList.each(function () {
            html += `
                <li class="list-group-item">
                    <input name="${this.dataset.type}[]" type="checkbox" value="${this.value}" class="form-check-input me-1" checked="checked">
                    ${this.value}
                </li>
            `;
        });
        $('#deleteModal .list-group').html(html);
        deleteModal.show();
    });
    $('#deleteModal').submit(function () {
        let submitButton = $(this).find('[type="submit"]');
        submitButton.addClass('disabled');

        fetch("<?=url('delete')?>", {
            body: new FormData(this)
            ,method: 'POST'
            ,credentials: 'same-origin'
            ,headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
            .then(response => response.json())
            .then(function (result) {
                submitButton.removeClass('disabled');

                if (0 == result.code) {
                    deleteModal.hide();
                    alert(result.msg);
                    location.reload();
                } else {
                    alert(result.msg);
                }
            })
            .catch(function (error) {
                submitButton.removeClass('disabled');
                alert('发生错误:' + error);
            });
        return false;
    });
</script>
</body>
</html>